import OperationCol from '@/components/OperationCol'
import SealStatus, { statusList } from '@/components/SealStatus'
import {
  adminTypes,
  formatStatus,
  orgLicenseTypes,
  orgTypes,
  useTypes,
  userLicenseTypes,
  sealTypes,
} from '@/lib/sealFormat'
import { desensitization } from '@/lib/utils'
import { RootState } from '@/store'
import { Component, Vue } from 'vue-property-decorator'
import { Action, Mutation, State } from 'vuex-class'
import { UserState } from '../../store/modules/user'
import styles from '../NewApply/NewApply.less'
import LossSeal from '../LossApply/LossSeal'
import { getTimeline } from '../../lib/sealFormat'
import { Table } from 'element-ui'
import TableEmpty from '@/components/tableEmpty'

// const statusList: any[] = [
// 	{
// 		id: 0,
// 		value: "全部"
// 	},
// 	{
// 		id: 1,
// 		value: "新增"
// 	},
// 	{
// 		id: 2,
// 		value: "待审核"
// 	}
// ];

@Component({})
export default class RecoverApply extends Vue {
  @State((state: RootState) => state.recoverApply.sealList)
  private sealList!: any[]
  @State((state: RootState) => state.recoverApply.total)
  private total!: number
  @State((state: RootState) => state.recoverApply.recoverVisible)
  private recoverVisible!: boolean
  @State((state: RootState) => state.recoverApply.detailVisible)
  private detailVisible!: boolean
  @State((state: RootState) => state.recoverApply.loading)
  private loading!: boolean
  @State((state: RootState) => state.recoverApply.applyData)
  private applyData!: any
  @State((state: RootState) => state.recoverApply.title)
  private title!: any
  @State((state: RootState) => state.user)
  private user!: UserState

  private sealType: number[] = []
  private status: number[] = []
  private sealName: string = ''
  private pageIndex: number = 1
  private pageSize: number = 10
  private applyTitle: string = '印章申请'
  private showTimeline: boolean = false
  private saveLoading: boolean = false
  private sealOption: any[] = []
  private sealApplyId = ''

  @Mutation('recoverApply/setStateData') private setStateData!: (
    data: any
  ) => {}
  @Action('recoverApply/getList') private getList!: any
  @Action('recoverApply/saveSeal') private saveSeal!: any
  @Action('recoverApply/saveAndSubmit') private saveAndSubmit!: any
  @Action('recoverApply/submitSeal') private submitSeal!: any
  @Action('recoverApply/sealDetail') private sealDetail!: any
  @Action('recoverApply/deleteApply') private deleteApply!: any

  protected render() {
    return (
      <div class="p10">
        <div class={{ [styles.query]: true, custom: true }}>
          <span class={styles.part}>
            <span>印章类别</span>
            <el-select
              v-model={this.sealType}
              multiple
              collapse-tags
              placeholder="默认全部"
            >
              {sealTypes.map((sealType: any, index: number) => (
                <el-option
                  key={sealType.id}
                  label={sealType.value}
                  value={sealType.id}
                />
              ))}
            </el-select>
          </span>
          {/* <span class={styles.part}>
						<span>印章状态</span>
						<el-select v-model={this.status} placeholder="请选择">
							{this.statusArry.map((sealType: any, index: number) => (
								<el-option key={sealType.key} label={sealType.text} value={sealType.key} />
							))}
						</el-select>
					</span> */}
          <span class={styles.part}>
            <span>申请编号</span>
            <el-input v-model={this.sealApplyId} />
          </span>
          <span class={styles.part}>
            <span>印章名称</span>
            <el-input v-model={this.sealName} />
          </span>
          <span class={styles.part}>
            <el-button
              onClick={this.query}
              loading={this.loading}
              plain
              class="min color-blue"
            >
              搜索
            </el-button>
            <el-button onClick={this.reset} plain class="min color-gray">
              重置
            </el-button>
          </span>
        </div>
        <el-table
          data={this.sealList}
          style="width: 100%"
          v-loading={this.loading}
          ref="table"
        >
          <TableEmpty
            v-show={!this.loading}
            slot="empty"
            msg="暂无匹配的印章恢复记录，您可前往申请印章列表或管理印章列表恢复已挂失的印章"
            url={require('@/assets/seal-empty.svg')}
          >
            <el-button onClick={this.toAppliedForMe}>
              前往管理印章列表
            </el-button>
            <el-button type="primary" onClick={this.toNewApply}>
              前往申请印章列表
            </el-button>
          </TableEmpty>
          <el-table-column
            prop="sealApplyRecordId"
            label="申请编号"
            min-width="170"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sealName"
            label="印章名称"
            min-width="170"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sealType"
            label="印章类别"
            min-width="80"
            show-overflow-tooltip
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return formatStatus(sealTypes, scope.row.sealType)
                },
              },
            }}
          />
          <el-table-column
            prop="organizeName"
            label="用章机构名称"
            min-width="170"
            show-overflow-tooltip
          />
          <el-table-column
            prop="createTime"
            label="创建时间"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column
            prop="sealApplyStatus"
            label="状态"
            min-width="120"
            show-overflow-tooltip
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return (
                    <SealStatus
                      statusData={{ color: '#52C41A', text: '已恢复' }}
                    />
                  )
                },
              },
            }}
          />

          <el-table-column
            prop="id"
            label="操作"
            width="210"
            {...{
              scopedSlots: {
                default: (scope: any) => {
                  return (
                    <OperationCol
                      operations={this.filterOpera(scope.row.sealApplyStatus)}
                      showNum={4}
                      row={scope.row}
                      index={scope.$index}
                    />
                  )
                },
              },
            }}
          />
        </el-table>
        {this.sealList && this.sealList.length > 0 && (
          <el-pagination
            class={{ [styles.pagination]: true }}
            onSize-change={this.handleSizeChange}
            onCurrent-change={this.handleCurrentChange}
            current-page={this.pageIndex}
            page-sizes={[10, 20, 30]}
            page-size={this.pageSize}
            layout="total, sizes, prev, pager, next, jumper"
            total={this.total}
            pager-count={5}
          />
        )}

        <LossSeal
          onVisibleChange={(val: boolean) => {
            this.setStateData({ recoverVisible: val })
          }}
          title={this.title}
          isEdit={false}
          data={this.applyData}
          isLoss={false}
          showSubmit={false}
          visible={this.recoverVisible}
        />
      </div>
    )
  }

  private mounted() {
    this.query()
  }

  get statusArry() {
    return [{ key: 0, text: '全部' }].concat(
      statusList.filter((item: any) => item.key !== 6)
    )
  }

  get agentInfo() {
    return {
      agentName: this.user.accountName,
      agentId: this.user.accountUUID,
      agentMobile: this.user.accountMobile,
      agentLicenseType: this.user.accountLicenseType,
      agentLicenseNumber: this.user.accountLicenseNumber,
      organizeName: this.user.organizeName,
      organizeUUID: this.user.organizeUUID,
      organizeType: this.user.organizeType,
      organizeAdministrationLevel: this.user.organizeAdministrationLevel,
      organizeLicenseType: this.user.organizeLicenseType,
      organizeLicenseNumber: this.user.organizeLicenseNumber,
      agentLicenseNumberDes: desensitization(
        this.user.accountLicenseNumber || ''
      ),
      agentMobileDes: desensitization(this.user.accountMobile || ''),
      sealName: this.user.organizeName,
    }
  }

  get getOperations() {
    const btns: any[] = [
      {
        id: 0,
        text: '详情',
        onClick: (index: number, rows: any) => {
          this.detail(rows)
        },
      },
    ]

    return btns
  }

  private filterOpera(status: number) {
    return status === 1
      ? this.getOperations
      : status === 90
      ? this.getOperations.filter((item: any) => item.id !== 1)
      : [this.getOperations[0]]
  }

  private query() {
    this.pageIndex = 1
    this.queryList()
  }
  private async queryList() {
    await this.getList(this)
    const table = this.$refs.table as Table
    table.doLayout()
  }

  private update(row: any) {
    this.applyTitle = '印章编辑'
    this.sealDetail(row.sealApplyId).then((data: any) => {
      this.setStateData({
        applyVisible: true,
        orgList: [
          {
            organizeName: data.applyOrganizeName,
            organizeUUID: data.applyOrganizeUuid,
            organizeAdministrationLevel: data.applyOrganizeLevel,
            organizeLicenseNumber: data.applyOrganizeLicenseNumber,
            organizeLicenseType: data.applyOrganizeLicenseType,
            organizeType: data.applyOrganizeType,
          },
        ],
        auditOrgList: [
          {
            organizeName: data.confirmOrganizeName,
            organizeUUID: data.confirmOrganizeUuid,
            organizeLicenseNumber: data.confirmOrganizeLicenseNumber,
            organizeLicenseType: data.confirmOrganizeLicenseType,
          },
        ],
        applyData: Object.assign({}, data, {
          agentLicenseNumber: data.agentLicenseNumber,
          agentLicenseType: data.agentLicenseType,
          agentName: data.agentName,
          agentMobile: data.agentMobile,
          organizeAdministrationLevel: data.applyOrganizeLevel,
          organizeLicenseNumber: data.applyOrganizeLicenseNumber,
          organizeLicenseType: data.applyOrganizeLicenseType,
          organizeName: data.applyOrganizeName,
          organizeType: data.applyOrganizeType,
          organizeUUID: data.applyOrganizeUuid,
          useType: data.sealUseType,
          sealType: data.sealType,
          sealName: data.sealName,
          auditOrganizeName: data.confirmOrganizeName,
          auditOrganizeLicenseType: data.confirmOrganizeLicenseType,
          auditOrganizeLicenseNumber: data.confirmOrganizeLicenseNumber,
          auditOrganizeUUID: data.confirmOrganizeUuid,
          fileKey: data.sealApplyFileKey,
          url: data.sealApplyFileUrl,
          agentLicenseNumberDes: desensitization(data.agentLicenseNumber || ''),
          agentMobileDes: desensitization(data.agentMobile || ''),
          sealApplyId: data.sealApplyId,
        }),
      })
      this.sealOption = getTimeline(data.sealApplyStatus, this.applyData)
      this.showTimeline = this.sealOption.length > 0
    })
  }

  private delete(row: any) {
    this.deleteApply(row.sealApplyId).then(() => {
      this.$message.success('删除成功')
      this.query()
    })
  }

  toNewApply() {
    this.$router.push({ name: 'newApply' })
  }

  toAppliedForMe() {
    this.$router.push({ name: 'myManagingSeal' })
  }

  private detail(row: any) {
    this.sealDetail(row.sealApplyId).then((data: any) => {
      this.setStateData({
        recoverVisible: true,
        title: '印章挂失恢复详情',
        applyData: Object.assign({}, data, {
          agentName: data.agentName,
          agentLicenseType: data.agentLicenseType,
          agentLicenseTypeName: formatStatus(
            userLicenseTypes,
            data.agentLicenseType
          ),
          agentMobile: data.agentMobile,
          agentLicenseNumber: data.agentLicenseNumber,
          agentLicenseNumberDes: desensitization(data.agentLicenseNumber || ''),
          agentMobileDes: desensitization(data.agentMobile || ''),
          reasonContent: data.applyReason,
          fileKey: data.sealApplyFileKey,
          url: data.sealApplyFileUrl,
          sealSn: row.sealSn,
          sealApplyId: data.sealApplyId,
          sealName: data.sealName,
          startTime: data.sealStartTime,
          endTime: data.sealEndTime,
          organizeName: data.applyOrganizeName,
          organizeCardType: formatStatus(
            orgLicenseTypes,
            data.applyOrganizeLicenseType
          ),
          organizeType: formatStatus(orgTypes, data.applyOrganizeType),
          organizeCardId: data.applyOrganizeLicenseNumber,
          organizeLevel: formatStatus(adminTypes, data.applyOrganizeLevel),
          sealType: formatStatus(sealTypes, data.sealType),
          sealUseType: formatStatus(useTypes, data.sealUseType),
        }),
      })
      this.sealOption = getTimeline(data.sealApplyStatus, this.applyData)
    })
  }

  private createForm(sealData: any) {
    sessionStorage.setItem(
      'sealInfo',
      JSON.stringify({
        organize: sealData.organizeName,
        orgType: formatStatus(orgTypes, sealData.organizeType),
        licenseType: formatStatus(
          orgLicenseTypes,
          sealData.organizeLicenseType
        ),
        licenseNumber: sealData.organizeLicenseNumber,
        agentName: sealData.agentName,
        agentLicenseType: formatStatus(
          userLicenseTypes,
          sealData.agentLicenseType
        ),
        agentLicenseNumber: sealData.agentLicenseNumber,
        agentMobile: sealData.agentMobile,
        sealName: sealData.sealName,
        useType: formatStatus(useTypes, sealData.useType),
        auditOrg: sealData.auditOrganizeName,
      })
    )
    window.open(`${window.location.origin}/applyForm`, '_blank')
  }

  private submit(row: any) {
    this.submitSeal(row.sealApplyId).then((res: any) => {
      this.query()
    })
  }

  private handleSizeChange(val: number) {
    this.pageIndex = 1
    this.pageSize = val
    this.queryList()
  }

  private handleCurrentChange(val: number) {
    this.pageIndex = val
    this.queryList()
  }

  private applySeal() {
    this.showTimeline = false
    this.applyTitle = '印章申请'
    this.setStateData({
      applyVisible: true,
      orgList: [
        {
          organizeName: this.user.organizeName,
          organizeUUID: this.user.organizeUUID,
          organizeAdministrationLevel: this.user.organizeAdministrationLevel,
          organizeLicenseNumber: this.user.organizeLicenseNumber,
          organizeLicenseType: this.user.organizeLicenseType,
          organizeType: this.user.organizeType,
        },
      ],
      auditOrgList: [],
      applyData: Object.assign({}, this.agentInfo),
    })
  }

  private reset() {
    this.sealType = []
    this.status = []
    this.sealName = ''
    this.sealApplyId = ''
    this.query()
  }

  private async save(data: any) {
    this.saveLoading = true
    this.saveSeal(data)
      .then((res: any) => {
        this.saveLoading = false
        this.query()
      })
      .catch((e: any) => {
        this.saveLoading = false
      })
  }

  private saveSubmit(data: any) {
    this.saveLoading = true
    this.saveAndSubmit(data)
      .then((res: any) => {
        this.saveLoading = false
        this.query()
      })
      .catch((e: any) => {
        this.saveLoading = false
      })
  }
}
